import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import cn from 'classnames';
import { Row, Col, Spin, Calendar } from 'antd';
import moment from 'moment';
import uniqueid from 'lodash.uniqueid';
import clone from 'lodash/clone';
import xss from 'xss';
import { getmycalendar } from '@/services/attendance/attendance';
import { dateConversion, dateConversion2 } from '@/utils/utils';
import { eventTrack } from '@/utils/track';
import { MoreBar } from '../common/TabBarExtraContent';
import styles from '../../homepage.less';
import indexs from './index.less';

/**
 * 异常数据进行处理
 * 组员对象进行对比，如果异常类型和名字一致的情况下修改内容值并生成新数组
 */
const exceptionDataProcessing = data => {
    const oldData = clone(data);
    const newArr = [];
    for (let i = 0; i < oldData.length; i += 1) {
        let exist = false;
        for (let d = i + 1; d < oldData.length; d += 1) {
            if (
                oldData[i].exceptionName === oldData[d].exceptionName &&
                oldData[i].exceptionDate === oldData[d].exceptionDate
            ) {
                exist = true;
                newArr.push({
                    ...oldData[i],
                    exceptionInterval: 3
                });
                oldData[d].oneDay = true;
                oldData[d].exceptionInterval = 3;
                oldData[d].countNum = 2;
                break;
            }
        }
        if (!exist) {
            newArr.push({
                ...oldData[i],
                oneDay: true
            });
        }
    }
    return newArr.filter(item => item.oneDay);
};

// eslint-disable-next-line no-inner-declarations
function goPage(item) {
    if (item.code === 'absence') {
        return {
            pathname: '/personal/portal/attendance/mine/abnormal',
            query: {
                date: moment(item.exceptionDate).format('YYYY-MM'),
                key: 'absencelist'
            }
        };
    }
    if (item.code === 'lackCard') {
        return {
            pathname: '/personal/portal/attendance/mine/abnormal',
            query: {
                date: moment(item.exceptionDate).format('YYYY-MM'),
                key: 'misslist'
            }
        };
    }
    if (item.code === 'lateOne' || item.code === 'lateTwo' || item.code === 'earlyOne' || item.code === 'earlyTwo') {
        return {
            pathname: '/personal/portal/attendance/mine/abnormal',
            query: {
                date: moment(item.exceptionDate).format('YYYY-MM'),
                key: 'latelist'
            }
        };
    }
    return '';
}

const callEventTrack = () => {
    eventTrack({
        eventName: 'portal_attendance_calendar_click',
        pageName: 'personal_portal'
    });
};

const Kqrl = props => {
    const { responders } = props;
    const { onAdd } = responders;

    const [spinning, setSpinning] = useState(false);
    const [abnormalDate, setAbnormalDate] = useState('');
    const [curInfo, setCurInfo] = useState({});
    const [today, setToday] = useState(null);
    const [initYear, setInitYear] = useState(moment().format('YYYY'));

    const layoutSpan = 24;

    const dateRender = current => {
        // console.log('dateRender', {
        //     current: current.format('YYYY-MM-DD'),
        //     T: T.format('YYYY-MM-DD')
        // });
        const {
            // holiday = [],
            exception = [],
            leave = [],
            myOverTime = [],
            myOutTimeVos = [],
            myTripTimeVos = []
        } = abnormalDate;
        // const hasHoliday = holiday.some(
        //     item => item.whichDay === current.format('YYYY-MM-DD')
        // );
        const hasException = exception.some(item => item.exceptionDate === current.format('YYYY-MM-DD'));
        const hasLeave = leave.some(
            item => moment(item.timeDetial).format('YYYY-MM-DD') === current.format('YYYY-MM-DD')
        );
        const hasMyOverTime = myOverTime.some(item => item.overDate === current.format('YYYY-MM-DD'));
        const hasMyOutTimeVos = myOutTimeVos.some(item => item.outDate === current.format('YYYY-MM-DD'));
        const hasMyTripTimeVos = myTripTimeVos.some(item => item.tripDate === current.format('YYYY-MM-DD'));
        if (
            // hasHoliday ||
            hasException ||
            hasLeave ||
            hasMyOverTime ||
            hasMyOutTimeVos ||
            hasMyTripTimeVos
        ) {
            return (
                <div style={{ position: 'relative' }}>
                    {/* {current.date()} */}
                    <div className="vv-date-dot" />
                </div>
            );
        }
        return null;
    };
    const getPayload = (
        startTime = moment()
            .startOf('year')
            .format('YYYY-MM-DD'),
        endTime = moment()
            .endOf('year')
            .format('YYYY-MM-DD')
    ) => {
        const user = JSON.parse(localStorage.getItem('user'));
        const payload = {
            companyCode: user.companyId,
            employeeCode: user.employeeCode,
            dayType: 2,
            leaveCode: [''],
            startTime,
            endTime,
            whichYear: moment().format('YYYY'),
            attandanceType: 123,
            typeCode: '',
            outTripOverStatus: ''
        };
        return payload;
    };
    const getTodayInfo = (T = moment(), source = {}) => {
        const {
            exception = [],
            leave = [],
            myOverTime = [],
            myOutTimeVos = [],
            myTripTimeVos = [],
            holiday = [],
            myAttendanceRecordVos = []
        } = source;
        const value = T.format('YYYY-MM-DD');

        const exceptionData = exceptionDataProcessing(exception);
        return (
            <div className={styles.event} onClick={callEventTrack}>
                {holiday.map(
                    () =>
                        // if (item.whichDay === value) {
                        //     return (
                        //         <div
                        //             className={styles.list}
                        //             key={uniqueid('holiday_list_')}
                        //         >
                        //             <b>{item.holidayName}</b>
                        //         </div>
                        //     );
                        // }
                        null
                )}
                {/* 签到 */}
                {myAttendanceRecordVos.map(item => {
                    if (item.signDate === value) {
                        if (item.signInTime && item.signInTime !== '') {
                            return (
                                <div
                                    className={styles.list}
                                    onClick={() =>
                                        history.push({
                                            pathname: '/personal/portal/attendance/mine/list/attendanceDetail',
                                            query: {
                                                date: moment(item.signDate).format('YYYY-MM')
                                            }
                                        })
                                    }
                                >
                                    <b>签到</b>
                                    <div>
                                        <span>{moment(item.signInTime).format('HH:mm')}</span>
                                    </div>
                                </div>
                            );
                        }
                    }
                    return null;
                })}
                {leave.map(item => {
                    if (moment(item.timeDetial).format('YYYY-MM-DD') === value) {
                        const particular = ['产假', '陪产假', '婚假', '孩童假', '附加产假', '丧假', '无薪儿童护理假'];
                        let html;
                        if (particular.indexOf(item.leaveName) > -1) {
                            html = moment(item.startTime).format('YYYY.MM.DD');
                            html += '-';
                            html += moment(item.endTime).format('YYYY.MM.DD');
                        } else {
                            html = moment(item.startTime).format('HH:mm');
                            html += '-';
                            html += moment(item.endTime).format('HH:mm');
                        }
                        return (
                            <div
                                className={styles.list}
                                key={uniqueid('leave_list_')}
                                onClick={() =>
                                    history.push({
                                        pathname: '/personal/portal/attendance/mine/holiday',
                                        query: {
                                            date: moment(item.timeDetial).format('YYYY-MM')
                                        }
                                    })
                                }
                            >
                                <b>{item.leaveName}</b>
                                <div>
                                    <span>{dateConversion(item.leaveLong, 8)}</span>
                                    <span>{html}</span>
                                </div>
                            </div>
                        );
                    }
                    return '';
                })}
                {exceptionData.map(item => {
                    if (item.exceptionDate === value) {
                        let html = '';
                        if (item.code === 'absence') {
                            html = `<b>${item.exceptionName}</b><span>${item.countNum}次</span>`;
                        } else if (item.code === 'lackCard') {
                            html = `<b>${item.exceptionName}${item.countNum}次</b>`;
                            html += '<i>详情</i>';
                            // if (item.exceptionInterval === 3) {
                            //     html += '上班卡，下班卡';
                            // } else if (item.exceptionInterval === 2) {
                            //     html += '下班卡';
                            // } else if (item.exceptionInterval === 1) {
                            //     html += '上班卡';
                            // }
                        } else if (
                            item.code === 'lateOne' ||
                            item.code === 'lateTwo' ||
                            item.code === 'earlyOne' ||
                            item.code === 'earlyTwo'
                        ) {
                            html = `<b>${item.exceptionName}</b><span>`;
                            html += item.exceptionName.substring(0, item.exceptionName.length - 1);
                            html += `${item.minute}分钟</span>`;
                        }
                        return (
                            <div
                                className={styles.list}
                                key={uniqueid('exception_list_')}
                                onClick={() => history.push(goPage(item))}
                                // eslint-disable-next-line react/no-danger
                                dangerouslySetInnerHTML={{
                                    __html: xss(html)
                                }}
                            />
                        );
                    }
                    return '';
                })}
                {myOverTime.map(item => {
                    if (item.overDate === value) {
                        return (
                            <div
                                className={styles.list}
                                key={uniqueid('myOverTime_list_')}
                                onClick={() =>
                                    history.push({
                                        pathname: '/personal/portal/attendance/mine/overList',
                                        query: {
                                            date: moment(item.overDate).format('YYYY-MM')
                                        }
                                    })
                                }
                            >
                                <b>加班</b>
                                <div>
                                    <span>{dateConversion2(item.overLong)}</span>
                                    <span>
                                        {moment(item.startTime).format('HH:mm')}-{moment(item.endTime).format('HH:mm')}
                                    </span>
                                </div>
                            </div>
                        );
                    }
                    return '';
                })}
                {myOutTimeVos.map(item => {
                    if (item.outDate === value) {
                        return (
                            <div
                                className={styles.list}
                                key={uniqueid('myOutTimeVos_list_')}
                                onClick={() =>
                                    history.push({
                                        pathname: '/personal/portal/attendance/mine/outList',
                                        query: {
                                            date: moment(item.outDate).format('YYYY-MM')
                                        }
                                    })
                                }
                            >
                                <b>外出</b>
                                <div>
                                    <span>{dateConversion2(item.outLong)}</span>
                                    <span>
                                        {moment(item.startTime).format('HH:mm')}-{moment(item.endTime).format('HH:mm')}
                                    </span>
                                </div>
                            </div>
                        );
                    }
                    return '';
                })}
                {myTripTimeVos.map(item => {
                    if (item.tripDate === value) {
                        return (
                            <div
                                className={styles.list}
                                key={uniqueid('myTripTimeVos_list_')}
                                onClick={() =>
                                    history.push({
                                        pathname: '/personal/portal/attendance/mine/tripList',
                                        query: {
                                            date: moment(item.tripDate).format('YYYY-MM')
                                        }
                                    })
                                }
                            >
                                <b>出差</b>
                                <div>
                                    <span>{dateConversion(item.tripLong, 8)}</span>
                                    <span>
                                        {moment(item.startTime).format('HH:mm')}-{moment(item.endTime).format('HH:mm')}
                                    </span>
                                </div>
                            </div>
                        );
                    }
                    return '';
                })}
                {/* 签退 */}
                {myAttendanceRecordVos.map(item => {
                    if (item.signDate === value) {
                        if (item.signOutTime && item.signOutTime !== '') {
                            return (
                                <div
                                    className={styles.list}
                                    onClick={() =>
                                        history.push({
                                            pathname: '/personal/portal/attendance/mine/list/attendanceDetail',
                                            query: {
                                                date: moment(item.signDate).format('YYYY-MM')
                                            }
                                        })
                                    }
                                >
                                    <b>签退</b>
                                    <div>
                                        <span>{moment(item.signOutTime).format('HH:mm')}</span>
                                    </div>
                                </div>
                            );
                        }
                    }
                    return null;
                })}
            </div>
        );
    };

    const initData = async (startTime, endTime) => {
        setSpinning(true);
        const res = await getmycalendar(getPayload(startTime, endTime));
        setSpinning(false);
        if (res && res.code === 10000) {
            setAbnormalDate(res.data);
        }
    };

    const changeDatePicker = v => {
        const date = v.format('YYYY-MM-DD');

        const {
            exception = [],
            leave = [],
            myOverTime = [],
            myOutTimeVos = [],
            myTripTimeVos = [],
            holiday = [],
            myAttendanceRecordVos = []
        } = abnormalDate;
        const leaves = leave.filter(item => moment(item.timeDetial).format('YYYY-MM-DD') === date);
        const exceptions = exception.filter(item => item.exceptionDate === date);
        const myOverTimes = myOverTime.filter(item => item.overDate === date);
        const myOutTimeVoss = myOutTimeVos.filter(item => item.outDate === date);
        const myTripTimeVoss = myTripTimeVos.filter(item => item.tripDate === date);
        const holidays = holiday.filter(item => item.whichDay === date);
        const myAttendanceRecordVoss = myAttendanceRecordVos.filter(item => item.signDate === date);

        const newCurInfo = {
            leave: leaves,
            exception: exceptions,
            myOverTime: myOverTimes,
            myOutTimeVos: myOutTimeVoss,
            myTripTimeVos: myTripTimeVoss,
            holiday: holidays,
            myAttendanceRecordVos: myAttendanceRecordVoss
        };
        setCurInfo(newCurInfo);
        setToday(v);
    };

    useEffect(() => {
        // TODO 拖拽时到不同列时子组件会重载
        initData();
    }, []);
    // useEffect(() => {
    //     getTodayInfo();
    // }, [curInfo]);
    // 登陆的时候默认获取当天事件
    useEffect(() => {
        changeDatePicker(moment());
    }, [abnormalDate]);

    return (
        <Spin spinning={spinning}>
            <Row>
                <Col span={layoutSpan}>
                    <div className={cn(styles.wnNoticeTitle, indexs.customPadding)}>
                        <h4>考勤月历</h4>
                        <MoreBar
                            linkProps={{
                                to: '/personal/portal/attendance/mine/list',
                                query: {},
                                onClick: (e, url) => {
                                    eventTrack({
                                        eventName: 'portal_attendance_calendar_more_click',
                                        pageName: 'personal_portal'
                                    });
                                    history.push(url);
                                }
                            }}
                            isDelete={false}
                            onAdd={onAdd}
                        />
                    </div>
                    <div className={indexs.wnDatePicker}>
                        {/* <DatePicker
                                        // onChange={this.onDateChange}
                                        open
                                        showToday={false}
                                        getCalendarContainer={() =>
                                            document.getElementById('area')
                                        }
                                        dateRender={dateRender}
                                        onChange={(m, d) => {
                                            changeDatePicker(m, d);
                                        }}
                                    /> */}
                        <Calendar
                            fullscreen={false}
                            dateCellRender={dateRender}
                            // monthCellRender={monthCellRender}
                            // onPanelChange={onPanelChange}
                            onChange={async v => {
                                const currentYear = v.format('YYYY');
                                if (currentYear !== initYear) {
                                    await initData(
                                        moment(currentYear).format('YYYY-MM-DD'),
                                        moment(currentYear)
                                            .endOf('year')
                                            .format('YYYY-MM-DD')
                                    );
                                    setInitYear(currentYear);
                                }

                                changeDatePicker(v);

                                callEventTrack();
                            }}
                        />
                    </div>
                </Col>
                <Col span={layoutSpan} className={cn(indexs.customPadding)}>
                    {getTodayInfo(today || moment(), curInfo)}
                    {/* <Button style={{ margin: '16px 0' }} onClick={() => history.push('/personal/portal/flow/mine/list')}>
                        异常申诉
                    </Button> */}
                </Col>
            </Row>
        </Spin>
    );
};
export default Kqrl;
